package pri.zey.custom.tools.impTools;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Timer;
import java.util.TimerTask;

import pri.zey.custom.AFMananger.CustomApplication;

/**
 * APK更新管理类
 */
public class UpdateManager {
    private static String TAG = "VersionUpdate";
    // 上下文对象
    private Context mContext;
    // 下载进度条
    private ProgressBar progressBar;
    // 是否终止下载
    private boolean isInterceptDownload = false;
    // 进度条显示数值
    private int progress = 0;
    private UpdateEntity entity;
    AlertDialog downloadDialog;

    /**
     * 声明一个handler来跟进进度条
     */
    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    // 更新进度情况
                    progressBar.setProgress(progress);
                    break;
                case 0:
                    progressBar.setVisibility(View.INVISIBLE);
                    downloadDialog.dismiss();
                    // 安装apk文件
                    installApk();
                    //Toast.makeText(mContext, "更新成功",Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break;
            }
        };
    };

    /**
     * 参数为Context(上下文activity)的构造函数
     */
    public UpdateManager(Context context, UpdateEntity entity) {
        this.mContext = context;
        this.entity = entity;
    }

    public String checkUpdate() {
        try {
            // 获取当前软件包信息
            PackageInfo pi = mContext.getPackageManager().getPackageInfo(
                    mContext.getPackageName(),
                    PackageManager.GET_CONFIGURATIONS);
            // 当前软件版本号
            float versionCode = Float.valueOf(pi.versionCode);
            System.out.println("现在使用的版本号:" + versionCode);
            float newVersionCode = Float.valueOf(entity.getVersion());
            System.out.println("最新的版本号:" + newVersionCode);
            // 如果当前版本号小于服务端版本号,则弹出提示更新对话框
            if (newVersionCode>versionCode) {

                try {
//                    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(MyApplication.getContext());
                    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(null);
                    // 新版本号
                    float newersionCode = Float.valueOf(entity.getVersion());

                    System.out.println("新版本号:" + newersionCode);
                    boolean ignoreVersion = prefs.getBoolean("ignore_version" + entity.getVersion(), false);
                    if (!ignoreVersion) {
                        showUpdateDialog();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            } else {
                return "1";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "2";// 网络连接失败
        }
        return "3";
    }

    /**
     * 提示更新对话框
     *
     *
     */

    private void showUpdateDialog() {
        Builder builder = new Builder(mContext);
        builder.setMessage(entity.getDescription());
        builder.setTitle("新车评客户端-版本更新"+entity.getVersion());
        builder.setPositiveButton("立刻更新", new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 弹出下载框
                dialog.dismiss();
                showDownloadDialog();
            }
            });
        builder.setNegativeButton("忽略此版本", new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
//                SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(MyApplication.getContext());
                SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(null);
                Editor pEdit = prefs.edit();
                pEdit.putBoolean("ignore_version" + entity.getVersion(), true);
                pEdit.apply();
                dialog.dismiss();
            }
            });
        builder.create().show();


    }

    /**
     * 弹出下载框
     */
    private void showDownloadDialog() {
        Builder downloadbuilder = new Builder(mContext);
        downloadbuilder.setTitle("版本更新中...");
        //builder.setIcon(R.drawable.logo);
        final LayoutInflater inflater = LayoutInflater.from(mContext);
        //View v = inflater.inflate(R.layout.update_prgress, null);
//        View v = View.inflate(mContext, R.layout.update_prgress, null);
//        progressBar = (ProgressBar) v.findViewById(R.id.pb_update_progress);
        View v = View.inflate(mContext, 0, null);
        progressBar = (ProgressBar) v.findViewById(0);
        downloadbuilder.setView(v);
        downloadbuilder.setNegativeButton("取消", new OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                // 终止下载
                isInterceptDownload = true;
            }
        });
        downloadDialog=downloadbuilder.create();
        downloadDialog.show();
        // 下载apk
        downloadApk();
    }

    /**
     * 下载apk
     */
    private void downloadApk() {
        // 开启另一线程下载
        Thread downLoadThread = new Thread(downApkRunnable);
        downLoadThread.start();
    }

    /**
     * 从服务器下载新版apk的线程
     */
    private Runnable downApkRunnable = new Runnable() {
        @Override
        public void run() {
            //初始化消息循环队列，需要在Handler创建之前
            Looper.prepare();

            if (!Environment.getExternalStorageState().equals(
                    Environment.MEDIA_MOUNTED)) {
                // 如果没有SD卡
                downloadDialog.dismiss();
                Timer timer = new Timer();
                timer.schedule(new TimerTask() {
                    public void run() {
                        Looper.prepare();
//                        Toast.makeText(CustomApplication.getAppContext(), "当前设备无SD卡，数据无法下载", Toast.LENGTH_SHORT).show();
                        Looper.loop();
                    }
                }, 100);
                return;
            } else {
                try {
                    // 服务器上新版apk地址
                    URL url = new URL(entity.getDownloadUrl());
                    //URL url = new URL("http://qd.shouji.360tpcdn.com/a5qapk/110016_gs1625930/com.qihoo.appstore_300030395.apk");
                    HttpURLConnection conn = (HttpURLConnection) url
                            .openConnection();
                    conn.connect();
                    int length = conn.getContentLength();
                    InputStream is = conn.getInputStream();
                    File file = new File(Environment
                            .getExternalStorageDirectory().getAbsolutePath()
                            + "/xincheping/");
                    Log.i(TAG, "下载apk的文件路径" + file.getPath());
                    if (!file.exists()) {
                        // 如果文件夹不存在,则创建
                        file.mkdir();
                    }
                    // 下载服务器中新版本软件（写文件）
                    String apkFile = Environment.getExternalStorageDirectory()
                            .getAbsolutePath()
                            + "/xincheping/"
                            + "xincheping"
                            + entity.getVersion() + ".apk";
                    File ApkFile = new File(apkFile);
                    FileOutputStream fos = new FileOutputStream(ApkFile);
                    int count = 0;
                    byte buf[] = new byte[1024];
                    do {
                        int numRead = is.read(buf);
                        count += numRead;
                        // 更新进度条
                        progress = (int) (((float) count / length) * 100);
                        Message message = handler.obtainMessage();
                        message.what = 1;
                        handler.sendEmptyMessage(1);
                        if (numRead <= 0) {
                            // 下载完成通知安装
                            handler.sendEmptyMessage(0);
                            break;
                        }
                        fos.write(buf, 0, numRead);
                        // 当点击取消时，则停止下载
                    } while (!isInterceptDownload);
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            //启动子线程消息循环队列
            Looper.loop();
        }
    };

    /**
     * 安装apk
     */
    private void installApk() {
        // 获取当前sdcard存储路径
        File apkfile = new File(Environment.getExternalStorageDirectory()
                .getAbsolutePath()
                + "/xincheping/"
                + "xincheping"
                + entity.getVersion() + ".apk");
        if (!apkfile.exists()) {
            return;
        }
        Intent i = new Intent(Intent.ACTION_VIEW);
        // 安装，如果签名不一致，可能出现程序未安装提示
        i.setDataAndType(Uri.fromFile(new File(apkfile.getAbsolutePath())),
                "application/vnd.android.package-archive");
        mContext.startActivity(i);
    }
}
